package 字符串;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * @Author Weton Li
 * @Date 2021/3/30 08:29
 */
public class 有效的括号 {


    private static final Map<Character, Character> map = new HashMap<Character, Character>() {{
        put('{', '}');
        put('[', ']');
        put('(', ')');
        put('?', '?'); // 栈为空，栈弹出元素会报错
    }};

    public static boolean isValid(String s) {
        if (s.length() > 0 && !map.containsKey(s.charAt(0))) {
            return false;
        }
        LinkedList<Character> stack = new LinkedList<Character>(){{
            add('?');
        }};

        for (char c : s.toCharArray()) {
            if (map.containsKey(c)) {
                stack.addLast(c);
            }else if(map.get(stack.removeLast())!=c) {
                return false;
            }
        }
        return stack.size() == 1;
    }


    public static void main(String[] args) {
        String s = "({[]})";
        System.out.println(isValid(s));

    }
}
